package com.cf.data.serve.controller;

import com.alibaba.fastjson.JSONObject;
import com.cf.data.serve.dto.SysLoginModel;
import com.cf.data.serve.utils.CommonConstant;
import com.cf.data.serve.utils.JwtUtil;
import com.cf.data.serve.utils.RedisUtil;
import com.cf.data.serve.utils.Result;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;

/**
 * @Author scott
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/sys")
@Slf4j
public class LoginController {

    @Autowired
    private RedisUtil redisUtil;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel, HttpServletRequest request) {
        Result<JSONObject> result = new Result<>();
        String username = sysLoginModel.getUsername();
        String password = sysLoginModel.getPassword();
        if (!username.equals("admin") && !password.equals("sdcf2024")){
            result.error500("用户名或密码错误");
            return result;
        }
        JSONObject obj = new JSONObject(new LinkedHashMap<>());
        //1.生成token
        String token = JwtUtil.sign(username, password);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        obj.put("token", token);
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }


}